package net.zoneland.zrdp.framework.web.service;

import java.util.*;
import java.util.stream.Collectors;

import org.springframework.stereotype.Component;

import net.zoneland.zrdp.common.core.domain.entity.SysUser;
import net.zoneland.zrdp.system.service.ISysMenuService;
import net.zoneland.zrdp.system.service.ISysRoleService;

import javax.annotation.Resource;

/**
 * 用户权限处理
 *
 * @author zonevue
 */
@Component
public class SysPermissionService
{
    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysMenuService menuService;

    /**
     * 获取角色数据权限
     *
     * @param user 用户信息
     * @return 角色权限信息
     */
    public Set<String> getRolePermission(final SysUser user) {
        final Set<String> roles = new HashSet<>();
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            roles.add("admin");
        } else {
            roles.addAll(roleService.selectRolePermissionByUserId(user.getUserId()));
        }
        return roles;
    }

    /**
     * 获取菜单数据权限
     *
     * @param user 用户信息
     * @return 菜单权限信息
     */
    public Set<String> getMenuPermission(final SysUser user) {
        if (user.isAdmin()) {
            return Collections.singleton("*:*:*");
        } else {
            return Optional.ofNullable(user.getRoles())
                .orElseGet(Collections::emptyList)
                .stream()
                .flatMap(role -> {
                    final Set<String> rolePerms = menuService.selectMenuPermsByRoleId(role.getRoleId());
                    role.setPermissions(rolePerms);
                    return rolePerms.stream();
                })
                .collect(Collectors.toSet());
        }
    }
}
